<?php 

/**
 * 返回Json数据
 * @param  [type] $data [description]
 * @return [type]       [description]
 */
function json_return($data)
{
    header('Content-Type:application/json; charset=utf-8');
    exit(json_encode($data));
}

/**
 * 封装的正确放回
 * @param  [type] $info [description]
 * @param  array $extend [description]
 * @return [type]       [description]
 */
function success($info = '', $extend = '')
{
    $data['code'] = 200;
    $data['info'] = $info;
    $data['data'] = $extend ? $extend : '';
    json_return($data);
}

/**
 * 封装的错误返回
 * @param  [type] $code [description]
 * @param  string $info [description]
 * @return [type]       [description]
 */
function error($code, $info = '')
{
    $data['code'] = $code;
    $data['info'] = $info;
    json_return($data);
}

/**
 * 获取设置请求数据
 * @param  [type] $data  [description]
 * @param  [type] $value [description]
 * @return [type]        [description]
 */
function request($data = null, $value = null)
{
    if (is_array($data)){
        $_REQUEST = array_merge($_REQUEST, $data);
        return $_REQUEST;
    }elseif ($data){
        if ($value === null){
            return $_REQUEST[$data];
        }else{
            $_REQUEST[$data] = $value;
        }
    }else{
        return $_REQUEST;
    }
}



/**
 * 记录调用
 * @param  [type] $path    [description]
 * @param  array  $request [description]
 * @return [type]          [description]
 */
function api_request_log($path, $request = [])
{
    #todo 后面实现
}


/**
 * 按照概率计算得到一个key 
 * 如果所有概率合为1  则必然返回一个Key 否则返回null
 * @param  [array] $item [key=>probability]
 * @return [string] key      [description]
 */
function roll($item)
{
    $sum = array_sum($item);
    if ($sum > 1) {
        // 概率总和大于1，等比例下调至概率总和为1
        $item = array_map(function($v) use ($sum) {
            return $v/$sum;
        }, $item);
    } else {
        // 概率总和不足1，剩余部分为未中奖概率
        $item['empty'] = 1 - $sum;
    }

    $random = mt_rand()/mt_getrandmax();

    $probability = 0;
    foreach ($item as $key => $value) {
        $probability += $value;
        if ($random < $probability && $key != 'empty') {
            return $key;
        }
    }
    return null;
}